package edu.zjut.hjg.saas.biz.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import edu.zjut.hjg.saas.biz.dao.SubscribeDao;
import edu.zjut.hjg.saas.biz.model.Subscribe;
import edu.zjut.hjg.saas.biz.support.AppStatus;
import edu.zjut.hjg.saas.biz.support.Paginated;

public class SubscribeDaoImpl extends SqlMapClientDaoSupport implements SubscribeDao {

    @Override
    public Integer create(Subscribe subscribe) {
        return (Integer) getSqlMapClientTemplate().insert("subscribe.create", subscribe);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Subscribe> listByKindergartenStatus(AppStatus status, int startId, int limit) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", status);
        params.put("startId", startId);
        params.put("limit", limit);
        return getSqlMapClientTemplate().queryForList("subscribe.listByKindergartenStatus", params);
    }

    @Override
    public Subscribe load(Integer id) {
        return (Subscribe) getSqlMapClientTemplate().queryForObject("subscribe.load", id);
    }

    @Override
    public void update(Subscribe subscribe) {
        getSqlMapClientTemplate().insert("subscribe.update", subscribe);
    }

    @Override
    public Subscribe findByKindergartenId(Integer kindergartenId) {
        return (Subscribe) getSqlMapClientTemplate().queryForObject(
                "subscribe.findByKindergartenId", kindergartenId);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Paginated<Subscribe> listByAppStatus(AppStatus status, int pageSize, int page) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", status);
        Integer totalSize = (Integer) getSqlMapClientTemplate().queryForObject(
                "subscribe.countByAppStatus", params);
        int start = pageSize * (page - 1);
        if (start > totalSize) {
            start = (totalSize / pageSize) * pageSize;
        }
        params.put("pageSize", pageSize);
        params.put("start", start);
        List<Subscribe> list = getSqlMapClientTemplate().queryForList("subscribe.listByAppStatus",
                params);
        Paginated<Subscribe> paginated = new Paginated<Subscribe>();
        paginated.setValues(list);
        paginated.setPageSize(pageSize);
        paginated.setStart(start);
        paginated.setTotalSize(totalSize);
        return paginated;
    }
}
